/*********************************************************
/*     Copyright (c) 2020 上海芯翌智能科技有限公司     
/*       公司内部代码, 未经允许, 不得使用和传播.       
**********************************************************/

#include "log.h"
#include "spdlog/async_logger.h"
#include "spdlog/details/thread_pool.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"
#include "spdlog/sinks/stdout_color_sinks.h"

namespace xffwcc {
namespace log {

spdlog::level::level_enum Logger::log_level_ = spdlog::level::level_enum::debug;
bool Logger::is_async_ = false;
std::shared_ptr<spdlog::logger> Logger::logger_ = nullptr;
std::shared_ptr<spdlog::details::thread_pool> Logger::th_pool_ = nullptr;
std::string Logger::default_pattern_ = "%Y-%m-%d %H:%M:%S %^%l%$ thread:%t %v";

void Logger::writeLog() {
  std::stringstream head;
  head << cpp_file_ << ":" << line_ << " "
       << " " << log_stream.ToString();

  switch (level_) {
    case LogLevel::trace:
      spdlog::trace(head.str());
      break;
    case LogLevel::debug:
      spdlog::debug(head.str());
      break;
    case LogLevel::info:
      spdlog::info(head.str());
      break;
    case LogLevel::warn:
      spdlog::warn(head.str());
      break;
    case LogLevel::err:
      spdlog::error(head.str());
      break;
    default:
      break;
  }
}

void Logger::init_logger(std::string filename, bool is_async,
                         uint64_t max_file_size, size_t max_files,
                         bool rotate_on_open) {
  if (filename.empty()) {
    std::cout << "logger filename null" << std::endl;
    exit(-1);
  }
  is_async_ = is_async;
  auto file_sink = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
      filename, max_file_size*kSizeM, max_files, rotate_on_open);
  auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
  spdlog::sinks_init_list sinks = {file_sink, console_sink};

  if (!is_async_) {
    logger_ = std::make_shared<spdlog::logger>("logger", sinks);
  } else {
    th_pool_ = std::make_shared<spdlog::details::thread_pool>(1000, 8);
    logger_ = std::make_shared<spdlog::async_logger>("logger", sinks, th_pool_);
  }
  if (logger_ != nullptr) {
    spdlog::set_default_logger(logger_);
    //log_level_ = level;
    spdlog::set_level(Logger::log_level_);
    spdlog::flush_on(spdlog::level::err);
    spdlog::flush_every(std::chrono::seconds(3));
    default_pattern_ = "%Y-%m-%d %H:%M:%S %^%l%$ thread:%t %v";
    Logger::set_pattern(default_pattern_);
  } else {
    std::cout << "init failed" << std::endl;
    exit(-1);
  }
}
}  // namespace log
}  // namespace xffwcc
